/*
 * @(#)AuthorStringTokenizer.java
 *
 * Copyright 2011 Xinhua Online, Inc. All rights reserved.
 */



import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * description XXX
 * @author  huangyixiang
 * @version 2011-10-18
 */
public class AuthorStringTokenizer {
	
	private static final Log LOG = LogFactory.getLog(AuthorStringTokenizer.class);
	
	private static Date newAuthorRuleDate;
	
	private static final String AUTHOR_NAME_REG = "\\s*(?:\\(.+?\\))?(.+?)(?:\\(.+?\\))?\\s*";
	
	private static final String AUTHOR_NAME_SPLIT_REG = ",|，";
	
	private static final String AUTHOR_REG = "\\s*(?:(.*?)\\s+等?\\s+著作)?\\s+(?:(.*?)\\s主编)?\\s+(?:(.*?)\\s编者)?\\s+(?:(.*?)\\s译者)?\\s*";
	
	private static final String[][] WORDS_ARRAY = {
		{
			"、",
			"," ,
			"，" ,
			"；" ,
			";",
			"\\(.*?\\)",
			"（.*?）",
			"//",
			"\\|",
			":",
			"等编著 ",
			"副?主编",
			"编著",
			"等译",
			"等文",
			"等图",
			"等著",
			"译者",
			"著作",
			"编者",
			"　",//放最后
		},
		{
			"([　 ]编)",
			"([　 ]等)",
			"([　 ]译)",
			"([　 ]著)",
		}
		
	};
	
	public static void main(String[] args) {
		String authorString = "(比利时)卢克、戴波德  　著 唐米  　译";
		String[] authors = getAuthors(authorString);
		for(String a :  authors){
			System.out.println(a);
		}
		for(String split : authors){
			try{
				authorString = authorString.replaceFirst(split, addUrl(split));
			}
			catch(Exception e ){
				LOG.info(e.getMessage(), e);
			}
		}
	}
	private static  String[] exceptWordsRegs = new String[WORDS_ARRAY.length];
	
	static {
		final String split = "|" ;
		StringBuilder sb;
		for(int i =0 ; i < WORDS_ARRAY.length ; i++){
			sb = new StringBuilder();
			for(String word : WORDS_ARRAY[i]){
				sb.append(split).append(word);
				
			}
			exceptWordsRegs[i] = sb.substring(1);
		}
		
		try {
			newAuthorRuleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-07-17 10:00:00");
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			LOG.info(e.getMessage(), e);
		}
	}
	
	public static String[] getAuthors(String authorString){
		
		for(String exceptWordsReg : exceptWordsRegs){
			System.out.println("exceptWordsReg = " + exceptWordsReg);
			authorString = authorString.replaceAll(exceptWordsReg, " ");
		}
		String[] authorSplit = authorString.trim().split("\\s+");
		for(int i = 0; i < authorSplit.length; i++){
			authorSplit[i] = authorSplit[i].trim();
		}
		
		return authorSplit; 
	}
	
	public static List<String>[] getAuthorsForNewRule(String authorString){

		Pattern p = Pattern.compile(AUTHOR_REG);
		Matcher m = p.matcher(authorString);
		if(!m.matches()){
			return null;
		}
		String[] authors = new String[]{m.group(1),
						m.group(2),
						m.group(3),
						m.group(4)};
		
		@SuppressWarnings("unchecked")
		List<String>[] list = new ArrayList[authors.length];
		for(int i = 0; i < list.length; i++){
			if(StringUtils.isBlank(authors[i])){
				list[i] = null;
			}
			else{
				System.out.println("authors[i]="+authors[i]);
				List<String> names = new ArrayList<String>();
				for(String authorFull : authors[i].split(AUTHOR_NAME_SPLIT_REG)){
					System.out.println("authorFull="+authorFull);
					if(!StringUtils.isBlank(authorFull)){
						Pattern p1 = Pattern.compile(AUTHOR_NAME_REG);
						Matcher m1 = p1.matcher(authorFull);
						if(!m1.matches()){
							System.out.println("m1.matches()=" + m1.matches());
							continue;
						}
						String authorName = m1.group(1);
						System.out.println(" authorName="+authorName);
						
						if(!StringUtils.isBlank(authorName)){
							names.add(authorName.trim());
						}
					}
				}
				list[i] = names;
			}
		}
		for(List<String> list1 : list){
			System.out.println("====================");
			if(list1 == null) continue;
			for(String authorName : list1){
				System.out.println(authorName);
			}
		}
		return list;
	}
	
	public static String getAuthorWithUrl(String authorString , Date createTime){
		if(StringUtils.isBlank(authorString)){
			return authorString;
		}
		
		if (createTime.after(newAuthorRuleDate)) {
			List<String>[] authorNamesList = getAuthorsForNewRule(authorString);
			Set<String> authorNamesSet = new HashSet<String>();
			for(List<String> list : authorNamesList){
				if(list == null || list.isEmpty()){
					continue;
				}
				for(String authorName : list){
					authorNamesSet.add(authorName);
				}
			}
			for(String authorName : authorNamesSet){
				String s =addUrl(authorName);
				authorString = authorString.replaceAll(authorName, s);
			}
			authorString = authorString.replaceFirst("\\s著作", " 著")
						.replaceFirst("\\s编者", " 编")
						.replaceFirst("\\s译者", " 译");
			return authorString;
			
		}
		else{
			String[] authors = getAuthors(authorString);
			for(String split : authors){
				try{
					authorString = authorString.replaceFirst(split, addUrl(split));
				}
				catch(Exception e ){
					LOG.info(e.getMessage(), e);
				}
			}
			return authorString;
		}
	}
	
	
	
	private static String addUrl(String author) {
		try {
			return "<a href=\"http://search.winxuan.com/search?author="
					+ URLEncoder.encode(author, "UTF-8")
					+ "\" style=\"color:#1D66B2\">" + author + "</a>";
		} catch (UnsupportedEncodingException e) {
			LOG.info(e.getMessage(), e);
		}
		return author;
	}
}
class StringUtils{
	public static boolean isBlank(String str){
		if(str == null || "".equals(str.trim())){
			return true;
		}
		return false;
	}
}